/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.antcloud.demo.antscheduler.nine1nine;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 *
 * @author qian.lqlq
 * @version $Id: WebSocketServer.java, v 0.1 2018年09月05日 20:16 qian.lqlq Exp $
 */
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebSocketServer {

    private static final Logger                         LOGGER       = LoggerFactory
        .getLogger(WebSocketServer.class);

    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    private Session                                     session;

    private String                                      userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketSet.add(this);
        System.out.println(userId + " open success");
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(userId + " open success");
        }
    }

    @OnClose
    public void onClose(Session session) {
        webSocketSet.remove(this);
        System.out.println(userId + " close success");
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(userId + " close success");
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        LOGGER.error(error.getMessage());
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        for (WebSocketServer server : webSocketSet) {
            synchronized (message.intern()) {
                server.getSession().getBasicRemote().sendText("alive");
            }
        }
    }

    public static void sendMessage(Map<String, PushMsg> msgMap) throws IOException {
        for (WebSocketServer server : webSocketSet) {
            if (msgMap.containsKey(server.getUserId())) {
                synchronized (server.getUserId().intern()) {
                    server.getSession().getBasicRemote()
                        .sendText(JSON.toJSONString(msgMap.get(server.getUserId())));
                }
            }
        }
    }

    public Session getSession() {
        return session;
    }

    public String getUserId() {
        return userId;
    }
}